<template>
  <a-modal
    v-model:visible="visible"
    centered
    wrap-class-name="region-dialog"
    :width="820"
    :after-close="handleAfterClose"
    :footer="footer"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>
      <slot name="title">区域选择</slot>
    </template>
    <scrollbar v-if="region.length" class="region-dialog__scrollbar">
      <div class="flex items-center">
        <a-checkbox :checked="checkedCity.length === allCityLen" @change="handleCheckAll">全选</a-checkbox>
        <a-select
          v-if="!lock"
          placeholder="在此处搜索推广区域"
          :value="getAllCitiesAndProvinces"
          class="region-selector"
          mode="multiple"
          show-search
          :max-tag-count="8"
          @select="handleSelectorChange"
          @deselect="handleDeSelectorChange"
        >
          <a-select-opt-group :key="province.id" v-for="province in region[0].children">
            <template #label>{{ province.name_cn }}</template>
            <a-select-option
              :value="city.name_cn"
              :province="province.name_cn"
              :key="city.id"
              v-for="city in province.children"
            />
          </a-select-opt-group>
        </a-select>
      </div>
      <div style="display: flex" v-if="props.loadis">
        <div style="width: 15%">
          <div style="margin-left: 20px; margin-top: 50px">省份</div>
        </div>
        <div style="width: 85%; display: flex; flex-wrap: wrap">
          <div :key="province.id" v-for="province in region[0].children">
            <div @click="handleCheckCitys(province.name_cn)" style="margin: 10px">
              {{ province.name_cn }}
            </div>
          </div>
        </div>
      </div>
      <div :key="province.id" v-for="province in region[0].children" class="flex mt-5">
        <a-checkbox
          :disabled="props.loadis"
          class="flex-shrink-0 region-province"
          :checked="innerCityMap[province.name_cn].length === province.children.length"
          @change="handleProvinceChange(province, $event)"
        >
          {{ province.name_cn }}
        </a-checkbox>
        <a-checkbox-group
          class="region-checkbox"
          :value="innerCityMap[province.name_cn]"
          :options="mapCityName(province.children)"
          @change="handleCheckCity(province.name_cn, $event)"
        />
      </div>
      <div class="flex mt-5">
        <div class="flex-shrink-0 region-province">
          <a-checkbox disabled></a-checkbox>
          <span class="ml-2 cursor-pointer">敬请期待</span>
        </div>
        <a-checkbox-group :value="[]" class="region-checkbox">
          <a-checkbox>香港</a-checkbox>
          <a-checkbox>澳门</a-checkbox>
          <a-checkbox>台湾</a-checkbox>
        </a-checkbox-group>
      </div>
    </scrollbar>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, reactive, watch, ref } from 'vue'
import { reactiveComputed, useVModel } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { useRegionStore, type Region } from '@/store/useRegionStore'
import Scrollbar from '@/components/scrollbar/index.vue'
import { cloneDeep } from 'lodash-es'
import is from '@/utils/is'
import { message } from 'ant-design-vue'

interface Props {
  show: boolean
  selected?: string
  footer?: string | null
  lock?: boolean
  max?: number
  loadis?: boolean
}

interface Emits {
  (e: 'change', v: string[]): void
  (e: 'limit', v: string[]): void
}

const props = withDefaults(defineProps<Props>(), {
  show: false,
  selected: '',
  footer: undefined,
  lock: false
})

const emit = defineEmits<Emits>()

const regionStore = useRegionStore()
const { region, mapChineseRegion, mapRegion } = storeToRefs(regionStore)
const visible = useVModel(props, 'show')

const selectedAreas = ref(new Set<string>())

const defaultCityMap = () => {
  return (
    (region.value[0]?.children ?? []).reduce<Record<string, string[]>>((init, province) => {
      init[province.name_cn] = []
      return init
    }, {}) ?? {}
  )
}

const innerCityMap = reactiveComputed(() => {
  const cityMap = defaultCityMap()
  selectedAreas.value.forEach((area) => {
    const province = findProvinceByCity(area)
    if (province && cityMap[province]) {
      cityMap[province].push(area)
    }
  })
  return cityMap
})

const allCityLen = computed(() => {
  return (region.value[0]?.children ?? []).reduce<number>((count, province) => {
    return count + province.children.length
  }, 0)
})

const checkedCity = computed(() => Array.from(selectedAreas.value))

const countryWide = computed(() => checkedCity.value.length === allCityLen.value)

function findProvinceByCity(city: string): string | null {
  for (const province of region.value[0]?.children || []) {
    if (province.children.some((c) => c.name_cn === city)) {
      return province.name_cn
    }
  }
  return null
}

function handleCheckCity(province: string, cities: string[], lock = props.lock) {
  if (lock) return

  selectedAreas.value = new Set([...selectedAreas.value].filter((area) => findProvinceByCity(area) !== province))

  cities.forEach((city) => selectedAreas.value.add(city))
}

function handleCheckCitys(province: string, lock = props.lock) {
  if (lock) return
  if (province === '直辖市') {
    return message.error('直辖市不能单独选择')
  }
  if (selectedAreas.value.has(province)) {
    selectedAreas.value.delete(province)
  } else {
    selectedAreas.value.add(province)
  }
}

// function handleProvinceChange(province: Region, value: any, lock = props.lock) {
//   if (lock) return
//   const checked = value.target.checked

//   if (checked) {
//     mapCityName(province.children).forEach((city) => selectedAreas.value.add(city))
//   } else {
//     selectedAreas.value = new Set(
//       [...selectedAreas.value].filter((area) => findProvinceByCity(area) !== province.name_cn)
//     )
//   }
// }
// 原有的
// function handleProvinceChange(province: Region, value: any, lock = props.lock) {
//   if (lock) return
//   const checked = value.target.checked

//   if (checked) {
//     mapCityName(province.children).forEach((city) => selectedAreas.value.add(city))

//     // 检查是否所有省份都被选中
//     const allProvincesSelected = region.value[0]?.children.every(
//       (p) => innerCityMap[p.name_cn].length === p.children.length
//     )

//     // 如果所有省份都被选中，添加"全国"
//     if (allProvincesSelected) {
//       selectedAreas.value.add('全国')
//     }
//   } else {
//     selectedAreas.value = new Set(
//       [...selectedAreas.value].filter((area) => {
//         // 移除该省份的城市
//         const isNotCurrentProvince = findProvinceByCity(area) !== province.name_cn
//         // 如果有任何省份未被完全选中，同时移除"全国"
//         return isNotCurrentProvince && area !== '全国'
//       })
//     )
//   }
// }

function handleProvinceChange(province: Region, value: any, lock = props.lock) {
  if (lock) return
  const checked = value.target.checked

  if (checked) {
    mapCityName(province.children).forEach((city) => selectedAreas.value.add(city))

    // 检查是否所有省份都被选中
    const allProvincesSelected = region.value[0]?.children.every(
      (p) => innerCityMap[p.name_cn].length === p.children.length
    )

    // 如果所有省份都被选中，添加"全国"
    if (allProvincesSelected) {
      selectedAreas.value.add('全国')
    }
  } else {
    selectedAreas.value = new Set(
      [...selectedAreas.value].filter((area) => {
        // 移除该省份的城市
        const isNotCurrentProvince = findProvinceByCity(area) !== province.name_cn
        // 如果有任何省份未被完全选中，同时移除"全国"
        return isNotCurrentProvince && area !== '全国'
      })
    )
  }
}

function mapCityName(city: Region[]) {
  return city.map((c) => c.name_cn)
}

function handleSelectorChange(value: string, option: any) {
  if (props.lock) return
  selectedAreas.value.add(value)
}

function handleDeSelectorChange(value: string, option: any) {
  if (props.lock) return
  selectedAreas.value.delete(value)
}

function handleCheckAll(e: any | boolean, lock = props.lock) {
  if (lock) return
  const checked = is.boolean(e) ? e : e.target.checked

  if (checked) {
    region.value[0]?.children.forEach((province) => {
      mapCityName(province.children).forEach((city) => selectedAreas.value.add(city))
    })
  } else {
    selectedAreas.value.clear()
  }
}
// function handleCheckAll(e: any | boolean, lock = props.lock) {
//   if (lock) return
//   const checked = is.boolean(e) ? e : e.target.checked

//   if (checked) {
//     region.value[0]?.children.forEach((province) => {
//       mapCityName(province.children).forEach((city) => selectedAreas.value.add(city))
//     })
//     selectedAreas.value.add('全国') // 全选时添加"全国"
//   } else {
//     selectedAreas.value.clear()
//   }
// }
// function handleCheckAll(e: any | boolean, lock = props.lock) {
//   if (lock) return
//   const checked = is.boolean(e) ? e : e.target.checked

//   if (checked) {
//     selectedAreas.value.clear() // 清空之前的选择
//     selectedAreas.value.add('全国') // 全选时添加"全国"
//   } else {
//     selectedAreas.value.clear()
//   }
// }

function handleOk() {
  if (is.number(props.max)) {
    if (selectedAreas.value.size > props.max) {
      emit('limit', Array.from(selectedAreas.value))
      return
    }
  }

  emit('change', Array.from(selectedAreas.value))
  visible.value = false
}

// watch(
//   () => [props.selected, props.show],
//   ([selected, show]) => {
//     if (!show) return

//     const makeAreas = selected.split(',')
//     selectedAreas.value = new Set(makeAreas)

//     if (makeAreas.some((area) => ['全国', '中国'].includes(area))) {
//       handleCheckAll(true, false)
//     }
//   }
// )
watch(
  () => [props.selected, props.show],
  ([selected, show]) => {
    if (!show) return

    const makeAreas = selected.split(',').filter((area) => area.trim()) // Filter out empty strings

    if (makeAreas && makeAreas.length > 0) {
      selectedAreas.value = new Set(makeAreas)
    }

    if (makeAreas.some((area) => ['全国', '中国'].includes(area))) {
      handleCheckAll(true, false)
    }
  }
)

// function handleCancel() {
//   selectedAreas.value = new Set(props.selected.split(','))
// }
function handleCancel() {
  // selectedAreas.value = new Set(props.selected.split(',').filter((area) => area.trim())) // Filter out empty strings
}
function handleAfterClose() {
  // 不需要额外操作，因为我们现在使用 selectedAreas
}

function handleReset() {
  selectedAreas.value.clear()
}

/*这里循环清除一下selectedAreas默认值中的""*/
// const getAllCitiesAndProvinces = computed(() => Array.from(selectedAreas.value))

defineExpose({
  handleReset,
  countryWide,
  selectedAreas
})
// 12/25早上更改有关全国的选项
// const getAllCitiesAndProvinces = computed(() => Array.from(selectedAreas.value).filter((area) => area !== ''))
const getAllCitiesAndProvinces = computed(() => {
  const areas = Array.from(selectedAreas.value).filter((area) => area !== '')
  // 如果选中了全国，返回一个包含"全国"的数组
  return areas.includes('全国') ? ['全国'] : areas
})
</script>

<style lang="scss" scoped>
.region {
  height: 80%;
}

.region-province {
  width: 90px;
  position: relative;
  border-right: 1px dashed grey;
}

.region-selector {
  width: 600px;
  margin-left: 70px;
}

.region-checkbox {
  padding-left: 30px;

  ::v-deep(.ant-checkbox) {
    display: none;
  }

  ::v-deep(.ant-checkbox + span) {
    padding: 2px 10px;
  }

  &::v-deep(.ant-checkbox.ant-checkbox-checked + span) {
    background: #ff4d4f;
    color: #fff;
    border-radius: 5px;
    padding: 2px 10px;
  }

  &::v-deep(.ant-checkbox-wrapper:nth-child(n + 12)) {
    margin-top: 8px;
  }
}
</style>

<style lang="scss">
.region-dialog {
  .ant-modal-content {
    height: 90vh;
    overflow: auto;
  }

  .ant-modal-body {
    height: calc(100% - 55px - 53px);
    padding-right: 0;
  }

  &__scrollbar {
    height: 100%;
    padding-right: 24px;
  }
}
</style>
